const puppeteer = require('puppeteer')
const url = 'https://movie.douban.com/tag/#/?sort=U&range=6,10&tags=' // 爬虫的地址

const sleep = time => new Promise(resolve => {
  setTimeout(resolve, time)
})

;(async () => { // 自动执行函数
  console.log('Start visit the target page')

  const browser = await puppeteer.launch({
    args: ['--no-sandbox'],
    dumpio: false
  })

  const page = await browser.newPage()
  await page.goto(url, {
    waitUntil: 'networkidle2'
  })

  await sleep(3000) // 3秒执行

  await page.waitForSelector('.more') // 加载页面数据摁扭

  for (let i = 0; i < 2; i++) { // 执行3个页面数据
    await sleep(3000)
    await page.click('.more')
  }

  const result = await page.evaluate(() => {
    var $ = window.$
    var items = $('.list-wp a') // 爬虫数据的层次级别
    var links = [] // 存储信息地址

    if (items.length >= 1) {
      items.each((index, item) => {
        let it = $(item)
        let doubanId = it.find('div').data('id') 
        let title = it.find('.title').text()
        let rate = Number(it.find('.rate').text())
        let poster = it.find('img').attr('src').replace('s_ratio', 'l_ratio')

        links.push({
          doubanId,
          title,
          rate,
          poster
        })
      })
    }

    return links
  })
  process.send({result}) // 进程发送信息
  process.exit(0)
  browser.close()
})()
